package com.jy.modules.cims.interact.service;

import java.text.MessageFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.jy.modules.cims.common.CimsIrtUrlConstant;
import com.jy.modules.cims.common.exception.InteractException;
import com.jy.modules.cims.component.common.service.TCMmDealInterfaceService;
import com.jy.modules.cims.data.common.dao.TCMmDealInterfaceDao;
import com.jy.modules.cims.data.common.dto.TCMmDealInterfaceDTO;
import com.jy.modules.cims.data.dao.SysAssistDao;
import com.jy.modules.cims.data.dto.DealInterfaceDto;
import com.jy.modules.cims.data.interact.core.credit.request.Request4041DTO;

/**
 * @description 监控服务
 * @version v1.0
 * @author ShengZhoutao
 * @Date 2012-9-27
 */
@Service("com.jy.modules.cims.interact.InteractJoinPoint")
@Aspect
public class InteractJoinPoint{
	private static final Logger logger = LoggerFactory.getLogger(InteractJoinPoint.class);
	
	@Autowired
	public SysAssistDao sysAssistDao;
	
	@Autowired
	public TCMmDealInterfaceDao tcmmDealInterfaceDao;
	
	@Autowired
    @Qualifier("com.jy.modules.cims.component.common.service.TCMmDealInterfaceService")
    private TCMmDealInterfaceService dealInterfaceService;

	@Around("execution(* com.jy.modules.cims.interact.InteractClient.sendReqToCore(..))")
	public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
		logger.info("@Around：开始验证是否处理超时过！");
		String frontTransNo = null;
		String dealCode = null;
        //访问目标方法的参数：
        Object[] args = proceedingJoinPoint.getArgs();
        if (args != null && args.length > 0 && args[0].getClass() == String.class) {
        	if(args[0].equals(CimsIrtUrlConstant.interactCfg.get(CimsIrtUrlConstant.IRT_CREDIT_TWO_BUY_TO_CORE).get(
                    CimsIrtUrlConstant.IRT_URL))){
        		Request4041DTO req = (Request4041DTO) args[1];
        		frontTransNo = this.getInterfaceCodeByDealCode(req.getApplyCode());
        		dealCode = req.getApplyCode();
        		if(frontTransNo!=null){
        			req.setFrontTransNo(frontTransNo);
        			args[1] = req;
        			logger.info("@Around：执行处理超时！");
        		}
        	}
        }
        //用改变后的参数执行目标方法
        Object returnValue = proceedingJoinPoint.proceed(args);
        logger.info("@Around：执行目标方法之后...");
        logger.info("@Around：被织入的目标对象为：" + proceedingJoinPoint.getTarget());
        if(frontTransNo!=null)
        this.deleteTCMmDealInterfaceByDealCode(dealCode);
        
        return returnValue;
		
	}
	/**
	 * 处理超时异常
	 * @Title doThrowing
	 * @Description TODO
	 * @param joinPoint
	 * @param exception 
	 * void 
	 * @date 2016-11-25-上午11:24:52
	 * @update 
	 * @throws
	 */
	@AfterThrowing(pointcut = "execution(* com.jy.modules.cims.interact.InteractClient.sendReqToCore(..))", throwing = "exception" )
	public void doThrowing(JoinPoint joinPoint, Throwable exception) {
		if (exception instanceof InteractException){
			Object[] args = joinPoint.getArgs();
			if (args != null && args.length > 0 && args[0].getClass() == String.class) {
	        	if(args[0].equals(CimsIrtUrlConstant.interactCfg.get(CimsIrtUrlConstant.IRT_CREDIT_TWO_BUY_TO_CORE).get(
	                    CimsIrtUrlConstant.IRT_URL))){
	        		Request4041DTO req = (Request4041DTO) args[1];
	        		try {
	        			if(this.getInterfaceCodeByDealCode(req.getApplyCode())==null)
	        			dealInterfaceService.insertTCMmDealInterface(req.getApplyCode(), req.getFrontTransNo());
					} catch (Exception e) {
						e.printStackTrace();
					}
	        	}
	        }
		}
		logger.error(MessageFormat.format("超时异常已经处理:{0}", exception.getMessage()));
	}

	/**
	 * 根据交易流水号获得接口流水号<br/>
	 * 单笔交易流水号可能对应多笔接口流水号，根据时间倒排序，取第一条接口返回
	 * 
	 * @param dealCode 交易流水号
	 * @return String 交易对应的接口流水号
	 * @author chenguixue
	 * @date 2015-1-26-下午5:20:40
	 * @update
	 */
	public String getInterfaceCodeByDealCode(String dealCode) throws Exception{
		Map<String, Object> searchParams = new HashMap<String, Object>();
		DealInterfaceDto dto = new DealInterfaceDto();
		dto.setDealCode(dealCode);
		searchParams.put("dto", dto);
		List<DealInterfaceDto> list = sysAssistDao.getInterfaceCodeByDealCode(searchParams);
		if (list != null && list.size() > 0) {
			return list.get(0).getFronttransno();
		}
		return null;
	}
	/**
	 * 
	 * @Title deleteTCMmDealInterfaceByDealCode
	 * @Description TODO
	 * @param dealCode 
	 * void 
	 * @date 2016-11-22-下午5:36:47
	 * @update 
	 * @throws
	 */
	public void deleteTCMmDealInterfaceByDealCode(String dealCode) throws Exception{
		Map<String, Object> paramMap = new HashMap<String, Object>();
		TCMmDealInterfaceDTO newDto = new TCMmDealInterfaceDTO();
		paramMap.put("dto", newDto);
		newDto.setDealCode(dealCode);
		sysAssistDao.deleteDealInterface(paramMap);
	}
}